import json
import re

from django.http import JsonResponse
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django_redis import get_redis_connection

from apps.users.models import User
from meiduo_mall import settings
from apps.oauth.models import OAuthQQUser
from django.contrib.auth import login


# Create your views here.
##### qq登录 ######
class QQLoginURLView(View):
    def get(self, request):
        # client_id 为官网获取的appid， client_secret 为官网获取的appkey
        # redirect_uri 为回调地址，可在QQ互联中设置 state=None
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state='xxxxx')
        # 调用对象的方法生成跳转链接
        qq_login_url = qq.get_qq_url()
        # 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'login_url': qq_login_url})


############ code获得token , 并获取openid 也就是qq回调页面############
class OauthQQView(View):
    ##### qq登录 ######
    def get(self, request):
        # 获取code
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '缺少code'})
        # 创建对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state='xxxxx')
        token = qq.get_access_token(code)
        # 获取openid
        openid = qq.get_open_id(token)
        # 根据openid查询用户是否存在
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 不存在
            # 如果没有绑定过,需要绑定
            response = JsonResponse({'code': 400, 'access_token': openid})
            return response
        else:
            # 存在
            # 如果已经绑定过,直接登录
            # 设置session
            login(request, qquser.user)
            # 设置cookie
            response = JsonResponse({'code': 0, 'errmsg': 'OK'})
            response.set_cookie('username', qquser.user.username)
            return response

    ### 如果没绑定过,需要绑定#####
    def post(self, request):
        # 获取参数
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code_client = data.get('sms_code')
        openid = data.get('access_token')
        # # 校验参数
        # if not all([mobile, password, sms_code_client, openid]):
        #     return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # # 校验手机号是否合法
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return JsonResponse({'code': 400, 'errmsg': '请输入正确的手机号码'})
        # # 校验密码是否合格
        # if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
        #     return JsonResponse({'code': 400, 'errmsg': '请输入8-20位的密码'})
        # # 校验短信验证码是否正确
        # #  创建redis连接对象
        # redis_conn = get_redis_connection('code')
        # # 获取redis中的短信验证码
        # sms_code_server = redis_conn.get('sms_%s' % mobile)
        # if sms_code_server is None:
        #     return JsonResponse({'code': 400, 'errmsg': '短信验证码已过期'})
        # # 对比短信验证码
        # if sms_code_client != sms_code_server.decode():
        #     return JsonResponse({'code': 400, 'errmsg': '短信验证码错误'})

        # 根据手机号查询用户是否存在
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 如果用户不存在,新建用户
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 如果用户存在,校验密码是否正确
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '账户或密码错误'})
        OAuthQQUser.objects.create(user=user, openid=openid)
        # 完成状态保持
        login(request, user)
        # 返回响应
        response = JsonResponse({'code': 0, 'errmsg': 'OK'})
        response.set_cookie('username', user.username)
        return response


# # 加密openid
# from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
# s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
# s.dumps({'openid': '1234567890'})

